<template>
  <basic-dialog
    title="修改账号"
    :width="480"
    :loading="loading"
    :visible="visible"
    @open="handleOpen"
    @closed="handleClosed"
    @submit="handleSubmit"
  >
    <el-form
      ref="formRef"
      :key="formKey"
      :model="formState"
      label-position="right"
      :label-width="60"
      :rules="rules"
      require-asterisk-position="right"
    >
      <el-form-item label="账号" class="mb-0" prop="username">
        <el-input v-model="formState.username" placeholder="请输入账号" />
      </el-form-item>
    </el-form>
  </basic-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormItemRule } from 'element-plus'

interface IProps {
  visible: boolean
}

interface IEmits {
  (event: 'closed'): void
  (event: 'submit'): void
  (event: 'update:visible', value: boolean): void
}

defineProps<IProps>()
const emit = defineEmits<IEmits>()

const userInfo = computed(() => useAppStore().userInfo)
const formRef = ref<FormInstance>()
const formKey = ref(Date.now())
interface FormState {
  username: string
}
const formState = reactive<FormState>({
  username: ''
})
const rules: Record<keyof FormState, FormItemRule[]> = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    {
      trigger: 'blur',
      validator: accountValidate
    }
  ]
}
const loading = ref(false)
async function handleSubmit() {
  await formRef.value?.validate()
  loading.value = true
  updateUserApi(formState)
    .then(() => {
      ToastUtils.success('操作成功')
      useAppStore().userInfoAction()
      emit('update:visible', false)
    })
    .finally(() => (loading.value = false))
}

function handleClosed() {
  emit('update:visible', false)
  emit('closed')
  formKey.value = Date.now()
}
function handleOpen() {
  formState.username = userInfo.value?.username
}
</script>

<style lang="scss" scoped></style>
